package com.zhu.user.service.impl;

import com.zhu.user.dao.UserMapper;
import com.zhu.user.model.User;
import com.zhu.user.model.UserCriteria;
import com.zhu.user.service.AuthService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by DELL on 2016/1/5.
 */
@Service("authService")
public class AuthServiceImpl implements AuthService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void login(String username, String password) {
        UsernamePasswordToken token = new UsernamePasswordToken();
        token.setUsername(username);
        token.setPassword(password.toCharArray());
        token.setRememberMe(true);

        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
    }

    @Override
    public User getCurrentUser() {
        UserCriteria userCriteria = new UserCriteria();
        userCriteria.createCriteria().andUsernameEqualTo(getCurrentUsername());

        List<User> userList = userMapper.selectByExample(userCriteria);
        if(userList != null && !userList.isEmpty()){
            return userList.get(0);
        }

        return null;
    }

    @Override
    public String getCurrentUsername() {
        try {
            return (String)SecurityUtils.getSubject().getPrincipal();
        }catch(Exception e){
            return null;
        }
    }

}
